﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AresCustomYacht
{
    public static class Utility
    {
        private const string Key = "K6u8#m2a";
        private static readonly DAL _dal = new DAL();

        public static string Encrypt(string value)
        {
            if (string.IsNullOrEmpty(value)) return null;

            byte[] iv = {0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78};
            byte[] key = Encoding.UTF8.GetBytes(Key);
            using (var oDesCrypto = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(value);
                var oMemoryStream = new MemoryStream();
                var oCryptoStream = new CryptoStream(oMemoryStream,
                                                     oDesCrypto.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                oCryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                oCryptoStream.FlushFinalBlock();
                return Convert.ToBase64String(oMemoryStream.ToArray());
            }
        }

        public static string Decrypt(string stringToDecrypt)
        {
            if (string.IsNullOrEmpty(stringToDecrypt)) return null;
            byte[] iv = {0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78};
            stringToDecrypt = stringToDecrypt.Replace(" ", "+");

            byte[] key = Encoding.UTF8.GetBytes(Key);
            var des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            Encoding encoding = Encoding.UTF8;
            return encoding.GetString(ms.ToArray());
        }

        private static Dictionary<string, string> GetQueryStringDictionary(Page page)
        {
            string queryString = Decrypt(GetQueryStringKey(page));
            if (string.IsNullOrEmpty(queryString)) return new Dictionary<string, string>();
            queryString = queryString.TrimEnd('&');
            return queryString.Split('&').ToDictionary(p => p.Split('=')[0], x => x.Split('=')[1]);
        }

        private static string GetQueryStringKey(Page page)
        {
            if (page.Request.QueryString["K"] == null) return "";
            try
            {
                return page.Request.QueryString["K"];
            }
            catch (Exception exception)
            {
                throw new KeyNotFoundException(
                    "The page could not process the parameters passed to it, please logout and login in again.",
                    exception);
            }
        }

        public static string GetPageMessage(Page page)
        {
            Dictionary<string, string> dictionary = GetQueryStringDictionary(page);
            return dictionary != null && dictionary.ContainsKey("Message") ? dictionary["Message"] : "";
        }

        public static void DisplayPageMessage(Page page, Label label)
        {
            label.Text = GetPageMessage(page);
            label.Visible = true;
            //label.ForeColor = Color.Green; 
        }

        public static string GetInsertAddress(string pageAddress)
        {
            return GetModeAddress(pageAddress, 0, "");
        }

        public static string GetModeAddress(string pageAddress, PageMode mode, string additionalQueryString)
        {
            string additionalString = additionalQueryString;
            if (!additionalQueryString.StartsWith("&"))
                additionalString = "&" + additionalQueryString;

            return string.Format("{0}?k={1}", pageAddress, Encrypt("Mode=" + (int) mode + additionalString));
        }

        public static string GetRedirectAddress(string pageAddress, PageMode mode, string message,
                                                string additionalString)
        {
            return string.Format("{0}?k={1}", pageAddress,
                                 Encrypt(string.Format("Mode={0}&Message={1}&{2}", (int) mode, message, additionalString)));
        }


        public static int GetPageMode(Page page)
        {
            Dictionary<string, string> dictionary = GetQueryStringDictionary(page);
            return dictionary != null && dictionary.ContainsKey("Mode") ? int.Parse(dictionary["Mode"]) : 0;
        }

        public static string GetQueryStringItem(Page page, string itemName)
        {
            Dictionary<string, string> dictionary = GetQueryStringDictionary(page);
            return dictionary != null && dictionary.ContainsKey(itemName) ? dictionary[itemName] : "";
        }

        internal static void DisplayImage(GridViewRowEventArgs e, int imageCell, int imageId, string publicLevel)
        {
            var image = e.Row.Cells[imageCell].Controls[1] as Image;
            image.ImageUrl = string.Format("{0}Displayimage.aspx?ImageId={1}", publicLevel, imageId);
        }

        internal static void DisplayImage(GridViewRowEventArgs e, int imageCell, int storeId,
                                          Dictionary<int, int> imagesDictionary, string publicLevel)
        {
            int imageId = 0;
            if (imagesDictionary.ContainsKey(storeId))
                imageId = imagesDictionary[storeId];

            var image = e.Row.Cells[imageCell].Controls[1] as Image;
            image.ImageUrl = string.Format("{0}Displayimage.aspx?ImageId={1}", publicLevel, imageId);
        }




        public static void ApplyMode(PageMode mode, List<WebControl> btnInsert, List<WebControl> btnUpdate,
                                     List<WebControl> btnDelete)
        {
            ApplyMode(mode, btnInsert, btnUpdate, btnDelete, null, "", "", "");
        }

        public static void ApplyMode(PageMode mode, WebControl btnInsert, WebControl btnUpdate, WebControl btnDelete)
        {
            ApplyMode(mode, new List<WebControl> {btnInsert}, new List<WebControl> {btnUpdate},
                      new List<WebControl> {btnDelete});
        }

        public static void ApplyMode(PageMode mode, WebControl btnInsert, WebControl btnUpdate, WebControl btnDelete,
                                     Label lblName, string newName, string updateName, string deleteName)
        {
            ApplyMode(mode, new List<WebControl> {btnInsert}, new List<WebControl> {btnUpdate},
                      new List<WebControl> {btnDelete}, lblName, newName, updateName, deleteName);
        }


        public static void ApplyMode(PageMode mode, List<WebControl> btnInsert, List<WebControl> btnUpdate,
                                     List<WebControl> btnDelete, Label lblName, string newName, string updateName,
                                     string deleteName)
        {
            switch (mode)
            {
                case PageMode.Insert:
                    foreach (WebControl button in btnInsert)
                        button.Visible = true;
                    foreach (WebControl button in btnUpdate)
                        button.Visible = false;
                    foreach (WebControl button in btnDelete)
                        button.Visible = false;

                    if (lblName != null) lblName.Text = newName;
                    break;
                case PageMode.Update:
                    foreach (WebControl button in btnInsert)
                        button.Visible = false;
                    foreach (WebControl button in btnUpdate)
                        button.Visible = true;
                    foreach (WebControl button in btnDelete)
                        button.Visible = false;

                    if (lblName != null) lblName.Text = updateName;
                    break;
                case PageMode.Delete:
                    foreach (WebControl button in btnInsert)
                        button.Visible = false;
                    foreach (WebControl button in btnUpdate)
                        button.Visible = false;
                    foreach (WebControl button in btnDelete)
                        button.Visible = true;

                    if (lblName != null) lblName.Text = deleteName;
                    break;
                default:
                    break;
            }
        }
    }
}